package com.agent.utils;

import com.agent.entity.CourseSchedule;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ExcelParserUtils {

    // 解析 .xls 文件
    public List<CourseSchedule> parseExcel(MultipartFile file) throws IOException {
        List<CourseSchedule> courseSchedules = new ArrayList<>();

        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            throw new IOException("文件名不能为空");
        }

        // 使用 HSSFWorkbook 处理 .xls 文件
        try (InputStream fis = file.getInputStream();
             Workbook workbook = createWorkbook(fis, fileName)) { // 这里改为 HSSFWorkbook

            Sheet sheet = workbook.getSheetAt(0);
            String currentDay = "";

            for (int i = 2; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                // 获取星期几
                Cell dayCell = row.getCell(0);
                if (dayCell != null && dayCell.getCellType() == CellType.STRING &&
                        !dayCell.getStringCellValue().trim().isEmpty()) {
                    currentDay = dayCell.getStringCellValue().trim();
                }

                // 获取节次
                Cell periodCell = row.getCell(1);
                if (periodCell == null || periodCell.getCellType() != CellType.STRING) {
                    continue;
                }
                String period = periodCell.getStringCellValue().trim();

                // 获取课程信息
                Cell infoCell = row.getCell(2);
                if (infoCell == null || infoCell.getCellType() != CellType.STRING) {
                    continue;
                }
                String courseInfo = infoCell.getStringCellValue().trim();

                // 解析课程信息
                CourseSchedule course = parseCourseInfo(courseInfo, currentDay, period);
                if (course != null) {
                    // 设置用户ID
                    course.setUserId(UserContext.getUserId());
                    courseSchedules.add(course);
                }
            }
        }
        return courseSchedules;
    }

    private Workbook createWorkbook(InputStream inputStream, String fileName) throws IOException {
        if (fileName.endsWith(".xls")) {
            return new HSSFWorkbook(inputStream);
        } else if (fileName.endsWith(".xlsx")) {
            return new XSSFWorkbook(inputStream);
        } else {
            throw new IOException("不支持的文件格式: " + fileName);
        }
    }

    private CourseSchedule parseCourseInfo(String courseInfo, String day, String period) {
        try {
            // 使用正则表达式提取课程信息
            Pattern pattern = Pattern.compile("(.+?)\\s+上课时间:([^地点]+)地点:([^教师]+)教师:([^教学班]+)");
            Matcher matcher = pattern.matcher(courseInfo);

            if (matcher.find()) {
                String courseName = matcher.group(1).trim();
                String workWeek = matcher.group(2).trim();
                String location = matcher.group(3).trim();
                String teacher = matcher.group(4).trim();

                // 处理教师字段可能包含的多余信息
                if (teacher.contains("教学班")) {
                    teacher = teacher.split("教学班")[0].trim();
                }

                // 转换时间和日期
                LocalTime[] times = TimeConverter.convertPeriodToTime(period.replace("节", ""));
                int dayOfWeek = TimeConverter.convertDayToNumber(day);

                return CourseSchedule.builder()
                        .courseName(courseName)
                        .teacher(teacher)
                        .location(location)
                        .dayOfWeek(dayOfWeek)
                        .workWeek(workWeek)
                        .startTime(times[0])
                        .endTime(times[1])
                        .build();
            }
        } catch (Exception e) {
            System.err.println("解析课程信息失败: " + courseInfo);
            e.printStackTrace();
        }

        return null;
    }
}
